/**
 * Mermaid语法映射加载和验证工具
 * 专利协作写作平台 - 图形化拖拽功能模块
 */

import type {
    MermaidSyntaxMapping,
    ChartTypeMapping,
    ParseResult,
    CompatibilityReport,
    ChartType,
    MermaidNode,
    MermaidConnection,
    NodeTypeMapping,
    ConnectionTypeMapping
} from '../types'

/**
 * Mermaid语法解析器
 * 负责解析Mermaid代码并分析兼容性
 */
export class FlowChartMermaidSyntaxParser {
    private syntaxMapping: MermaidSyntaxMapping

    constructor(syntaxMapping: MermaidSyntaxMapping) {
        this.syntaxMapping = syntaxMapping
    }

    /**
     * 解析Mermaid代码
     */
    parse(mermaidCode: string): ParseResult {
        try {
            mermaidCode = this.filterHeaderCode(mermaidCode)
            const chartType = this.detectChartType(mermaidCode)
            const tokens = this.tokenize(mermaidCode)
            const ast = this.buildAST(tokens, chartType)
            const compatibility = this.analyzeCompatibility(ast)

            return {
                // chartHeader,
                chartType,
                ast,
                compatibility,
                nodes: ast.nodes,
                connections: ast.connections,
            }
        } catch (error) {
            console.error('Mermaid代码解析失败:', error)
            throw new Error('无法解析Mermaid代码')
        }
    }

    private filterHeaderCode(code: string) {
        return code.replace(/^---[\s\S]*?^---$/gm, '').trim();
    }

    /**
     * 检测图表类型
     */
    private detectChartType(code: string): ChartType | 'unknown' {
        let filter_code = code.replace(/---[\s\S]*?---/, '').trim();
        const lines = filter_code.split('\n')
            .map(line => line.trim())
            .filter(line => line.length > 0 &&
                !line.startsWith('%%')
            ) // 过滤注释行

        if (lines.length === 0) {
            return 'unknown'
        }

        const firstLine = lines[0].toLowerCase()
        // 检测流程图
        if (firstLine.startsWith('flowchart') || firstLine.startsWith('graph')) {
            return 'flowchart'
        }

        // 检测状态图
        if (firstLine.startsWith('statediagram')) {
            return 'stateDiagram'
        }

        // 检测序列图
        if (firstLine.startsWith('sequencediagram')) {
            return 'sequenceDiagram'
        }

        // 检测类图
        if (firstLine.startsWith('classdiagram')) {
            return 'classDiagram'
        }

        // 检测ER图
        if (firstLine.startsWith('erdiagram')) {
            return 'erDiagram'
        }

        // 检测饼图
        if (firstLine.startsWith('pie')) {
            return 'pie'
        }

        return 'unknown'
    }

    /**
     * 词法分析
     */
    private tokenize(code: string): string[] {
        // 简单的词法分析，实际实现需要更复杂的逻辑
        return code.split('\n')
            .map(line => line.trim())
            .filter(line => line.length > 0 && !line.startsWith('%%'))
    }

    /**
    * 构建抽象语法树
    */
    private buildAST(tokens: string[], chartType: ChartType | 'unknown'): any {
        const lines = tokens.map(line => line.trim()).filter(line => line.length > 0)
        const nodes: MermaidNode[] = []
        const connections: MermaidConnection[] = []

        for (const line of lines) {
            // 跳过图表声明行
            if (line.startsWith(chartType) || line.startsWith('graph') || line.startsWith('flowchart')) {
                continue
            }
            try {
                // 尝试解析连接
                if (this.parseConnection(line, nodes, connections)) {
                    continue
                }

                // 尝试解析单独的节点定义
                this.parseNode(line, nodes)
            } catch (error) {
                console.warn(`解析行失败: ${line}`, error)
            }
        }

        // 确保所有连接的节点都存在
        const declaredNodeIds = new Set(nodes.map(node => node.id))
        connections.forEach(conn => {
            if (!declaredNodeIds.has(conn.from)) {
                nodes.push({ id: conn.from, type: 'rect', text: conn.from })
                declaredNodeIds.add(conn.from)
            }
            if (!declaredNodeIds.has(conn.to)) {
                nodes.push({ id: conn.to, type: 'rect', text: conn.to })
                declaredNodeIds.add(conn.to)
            }
        })

        return {
            type: 'chart',
            chartType,
            nodes,
            connections,
            directives: []
        }
    }

    /**
     * 解析连接
     */
    private parseConnection(line: string, nodes: MermaidNode[], connections: MermaidConnection[]): boolean {
        // 更精确的连接模式匹配
        for (const pattern of this.syntaxMapping.supportedCharts[0].connections) {
            let regex
            if (pattern.hasLabel) {
                regex = new RegExp(`^([\\s\\S]+?)${pattern.syntax[0]}([\\s\\S]+?)${pattern.syntax[1]}([\\s\\S]+?)$`)
            } else {
                regex = new RegExp(`^([\\s\\S]+?)${pattern.syntax[0]}([\\s\\S]+)$`)
            }
            const match = line.match(regex)

            if (match && match[1] !== undefined) {
                const fromPart = match[1].trim()
                const connType = pattern.type
                let label: string | undefined
                let toPart: string

                // if (pattern.hasLabel) {
                if (pattern.hasLabel) {
                    label = match[2].trim()
                    toPart = match[3].trim()
                } else {
                    toPart = match[2].trim()
                }


                // 解析源节点和目标节点
                const fromNode = this.parseNodePart(fromPart)
                const toNode = this.parseNodePart(toPart)

                // 添加节点（如果不存在）
                if (fromNode && !nodes.some(n => n.id === fromNode.id)) {
                    nodes.push(fromNode)
                }
                if (toNode && !nodes.some(n => n.id === toNode.id)) {
                    nodes.push(toNode)
                }

                // 添加连接
                if (fromNode && toNode) {
                    connections.push({
                        from: fromNode.id,
                        to: toNode.id,
                        type: connType,
                        label: label
                    })
                    return true
                }
            }
        }

        return false
    }

    /**
     * 解析节点部分（从连接中提取）
     */
    private parseNodePart(part: string): MermaidNode | null {
        for (const pattern of this.syntaxMapping.supportedCharts[0].nodes) {
            const regex = new RegExp(`^([^(]+)\\${pattern.syntax[0]}([^)]+)\\${pattern.syntax[1]}$`);
            const match = part.match(regex)
            if (match) {
                return {
                    id: match[1],
                    type: pattern.type,
                    text: match[2] || match[1]
                }
            }
        }

        // 如果没有匹配的模式，当作简单ID处理
        return {
            id: part,
            type: 'rect',
            text: part
        }
    }

    /**
     * 解析单独的节点定义
     */
    private parseNode(line: string, nodes: MermaidNode[]): boolean {
        const node = this.parseNodePart(line)
        if (node && !nodes.some(n => n.id === node.id)) {
            nodes.push(node)
            return true
        }
        return false
    }

    /**
     * 分析兼容性
     */
    private analyzeCompatibility(ast: any): CompatibilityReport {
        const chartMapping = this.syntaxMapping.supportedCharts.find(
            (chart: ChartTypeMapping) => chart.type === ast.chartType
        )

        if (!chartMapping) {
            return {
                overall: 'none',
                warnings: [],
                errors: [{
                    type: 'unsupported_chart_type',
                    message: `不支持的图表类型: ${ast.chartType}`
                }],
                supportedFeatures: [],
                unsupportedFeatures: [ast.chartType]
            }
        }

        if (!chartMapping.supported) {
            return {
                overall: 'none',
                warnings: [],
                errors: [{
                    type: 'chart_type_disabled',
                    message: `图表类型 "${ast.chartType}" 当前未启用`
                }],
                supportedFeatures: [],
                unsupportedFeatures: [ast.chartType]
            }
        }

        // 简化的兼容性分析，实际实现需要分析所有节点和连接
        return {
            overall: 'full',
            warnings: [],
            errors: [],
            supportedFeatures: [ast.chartType],
            unsupportedFeatures: []
        }
    }
}

/**
 * Mermaid代码生成器
 * 负责从可视化图表生成Mermaid代码
 */
export class FlowChartMermaidCodeGenerator {
    private syntaxMapping: MermaidSyntaxMapping

    constructor(syntaxMapping: MermaidSyntaxMapping) {
        this.syntaxMapping = syntaxMapping
    }

    /**
     * 从可视化图表生成Mermaid代码
     */
    generate(visualChart: any): string {
        try {
            const chartMapping = this.syntaxMapping.supportedCharts.find(
                (chart: ChartTypeMapping) => chart.type === visualChart.type
            )

            if (!chartMapping) {
                throw new Error(`不支持的图表类型: ${visualChart.type}`)
            }

            if (!chartMapping.supported) {
                throw new Error(`图表类型 "${visualChart.type}" 当前未启用`)
            }

            let code = this.generateHeader(visualChart.type, visualChart.direction)
            code += this.generateNodes(visualChart.nodes, chartMapping)
            code += this.generateConnections(visualChart.connections, chartMapping)
            code += this.generateDirectives(visualChart.directives)

            return this.formatCode(code)
        } catch (error) {
            console.error('代码生成失败:', error)
            throw error
        }
    }

    /**
     * 生成图表头部
     */
    private generateHeader(type: string, direction?: string): string {
        switch (type) {
            case 'flowchart':
                return `flowchart ${this.validateDirection(direction || 'TD')}\n`
            case 'stateDiagram':
                return 'stateDiagram-v2\n'
            case 'sequenceDiagram':
                return 'sequenceDiagram\n'
            case 'classDiagram':
                return 'classDiagram\n'
            case 'erDiagram':
                return 'erDiagram\n'
            case 'pie':
                return 'pie title Chart\n'
            default:
                return `${type}\n`
        }
    }

    /**
     * 验证方向参数
     */
    private validateDirection(direction: string): string {
        const validDirections = ['TD', 'TB', 'LR', 'RL', 'BT']
        return validDirections.includes(direction.toUpperCase()) ? direction.toUpperCase() : 'TD'
    }

    /**
     * 生成节点代码
     */
    private generateNodes(nodes: any[], chartMapping: ChartTypeMapping): string {
        if (!nodes || nodes.length === 0) {
            return ''
        }


        const nodeDefinitions = new Set<string>()
        const nodeLines: string[] = []

        nodes.forEach(node => {
            if (!node.id || !node.text) {
                console.warn('节点缺少必要信息:', node)
                return
            }

            const nodeMapping = chartMapping.nodes.find(n => n.type === node.type)
            if (!nodeMapping) {
                console.warn(`找不到节点类型映射: ${node.type}，使用默认矩形`)
                nodeLines.push(`    ${this.sanitizeId(node.id)}[${this.sanitizeText(node.text)}]`)
                nodeDefinitions.add(node.id)
                return
            }

            // if (nodeMapping.supportLevel === 'none') {
            //   console.warn(`节点类型 "${node.type}" 不支持，使用默认矩形`)
            //   nodeLines.push(`    ${this.sanitizeId(node.id)}[${this.sanitizeText(node.text)}]`)
            //   nodeDefinitions.add(node.id)
            //   return
            // }

            const nodeLine = this.formatNodeSyntax(node.id, node.text, nodeMapping)
            nodeLines.push(nodeLine)
            nodeDefinitions.add(node.id)
        })

        return nodeLines.length > 0 ? nodeLines.join('\n') + '\n' : ''
    }

    /**
     * 格式化节点语法
     */
    private formatNodeSyntax(id: string, text: string, nodeMapping: NodeTypeMapping): string {
        const cleanId = this.sanitizeId(id)
        const cleanText = this.sanitizeText(text)

        // 处理降级情况
        if (nodeMapping.supportLevel === 'partial' && nodeMapping.fallback) {
            return this.formatNodeByType(cleanId, cleanText, nodeMapping)
        }

        return this.formatNodeByType(cleanId, cleanText, nodeMapping)
    }

    /**
     * 根据类型格式化节点
     */
    private formatNodeByType(id: string, text: string, nodeMapping: NodeTypeMapping): string {
        // switch (type) {
        //   case 'rect':
        //     return `    ${id}[${text}]`
        //   case 'rounded':
        //   case 'round':
        //     return `    ${id}(${text})`
        //   case 'circle':
        //     return `    ${id}((${text}))`
        //   case 'diamond':
        //     return `    ${id}{${text}}`
        //   case 'cylindrical':
        //     return `    ${id}[(${text})]`
        //   case 'stadium':
        //     return `    ${id}([${text}])`
        //   case 'subroutine':
        //     return `    ${id}[[${text}]]`
        //   case 'asymmetric':
        //     return `    ${id}>${text}]`
        //   case 'hexagon':
        //     return `    ${id}{{${text}}}`
        //   case 'parallelogram':
        //     return `    ${id}[/${text}/]`
        //   case 'trapezoid':
        //     return `    ${id}[\\${text}/]`
        //   default:
        //     return `    ${id}[${text}]`
        // }
        return `    ${id}${nodeMapping.syntax_export[0]}${text}${nodeMapping.syntax_export[1]}`
    }

    /**
     * 生成连接代码
     */
    private generateConnections(connections: any[], chartMapping: ChartTypeMapping): string {
        if (!connections || connections.length === 0) {
            return ''
        }

        const connectionLines: string[] = []

        connections.forEach(conn => {
            if (!conn.from || !conn.to) {
                console.warn('连接缺少必要信息:', conn)
                return
            }

            // const connMapping = chartMapping.connections.find(c => c.type === conn.type)
            let connMapping: ConnectionTypeMapping | undefined;
            const bool = conn.label == undefined||conn.label == '' ? false : true
            chartMapping.connections.forEach(c => {
                if (c.type === conn.type && c.hasLabel === bool) {
                    connMapping = c
                }
            })
            if (!connMapping) {
                console.warn(`找不到连接类型映射: ${conn.type}，使用默认箭头`)
                connectionLines.push(`    ${this.sanitizeId(conn.from)} --> ${this.sanitizeId(conn.to)}`)
                return
            }

            if (connMapping.supportLevel === 'none') {
                console.warn(`连接类型 "${conn.type}" 不支持，使用默认箭头`)
                connectionLines.push(`    ${this.sanitizeId(conn.from)} --> ${this.sanitizeId(conn.to)}`)
                return
            }

            const syntax = connMapping.syntax_export[0] || '-->'
            const connLine = this.formatConnectionSyntax(conn.from, conn.to, conn.label, syntax, connMapping)
            connectionLines.push(connLine)
        })

        return connectionLines.length > 0 ? connectionLines.join('\n') + '\n' : ''
    }

    /**
     * 格式化连接语法
     */
    private formatConnectionSyntax(from: string, to: string, label: string | undefined, syntax: string, connMapping: ConnectionTypeMapping): string {
        const cleanFrom = this.sanitizeId(from)
        const cleanTo = this.sanitizeId(to)
        const cleanLabel = label ? this.sanitizeText(label) : ''

        // 处理标签
        if (cleanLabel !== '') {
            return this.formatConnectionWithLabel(cleanFrom, cleanTo, cleanLabel, connMapping)
        } else {
            return this.formatConnectionWithoutLabel(cleanFrom, cleanTo, syntax)
        }
    }

    /**
     * 格式化带标签的连接
     */
    private formatConnectionWithLabel(from: string, to: string, label: string, connMapping: ConnectionTypeMapping): string {
        // 根据语法类型决定标签格式
        return `    ${from} ${connMapping.syntax_export[0]}${label}${connMapping.syntax_export[1]} ${to}`

    }

    /**
     * 格式化无标签的连接
     */
    private formatConnectionWithoutLabel(from: string, to: string, syntax: string): string {
        return `    ${from} ${syntax} ${to}`
    }

    /**
     * 生成指令代码
     */
    private generateDirectives(directives: any[]): string {
        if (!directives || directives.length === 0) {
            return ''
        }

        const directiveLines: string[] = []

        directives.forEach(directive => {
            if (!directive.type || !directive.value) {
                console.warn('指令缺少必要信息:', directive)
                return
            }

            switch (directive.type) {
                case 'class':
                    directiveLines.push(`    class ${directive.value}`)
                    break
                case 'style':
                    directiveLines.push(`    style ${directive.value}`)
                    break
                case 'click':
                    directiveLines.push(`    click ${directive.value}`)
                    break
                default:
                    directiveLines.push(`    ${directive.type}: ${directive.value}`)
            }
        })

        return directiveLines.length > 0 ? directiveLines.join('\n') + '\n' : ''
    }

    /**
     * 清理ID
     */
    private sanitizeId(id: string): string {
        // 确保ID符合Mermaid规范
        return id
            .replace(/[^a-zA-Z0-9_-]/g, '_')
            .replace(/^[^a-zA-Z]/, 'n_')
            .slice(0, 50) // 限制长度
    }

    /**
     * 清理文本内容
     */
    private sanitizeText(text: string): string {
        if (!text) return ''

        // 移除或转义特殊字符
        return text
            .replace(/\r\n/g, ' ')
            .replace(/\n/g, ' ')
            .replace(/\t/g, ' ')
            .replace(/\s+/g, ' ')
            .replace(/[<>]/g, '')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/\[/g, '&#91;')
            .replace(/\]/g, '&#93;')
            .replace(/\{/g, '&#123;')
            .replace(/\}/g, '&#125;')
            .replace(/\(/g, '&#40;')
            .replace(/\)/g, '&#41;')
            .replace(/\|/g, '&#124;')
            .trim()
            .slice(0, 100) // 限制长度
    }

    /**
     * 格式化整个代码
     */
    private formatCode(code: string): string {
        return code
            .split('\n')
            .map(line => line.trimRight())
            .join('\n')
            .replace(/\n{3,}/g, '\n\n')
            .trim()
    }

    /**
     * 验证生成的代码
     */
    validateGeneratedCode(code: string): { isValid: boolean; errors: string[] } {
        const errors: string[] = []

        // 检查基本结构
        if (!code.trim()) {
            errors.push('生成的代码为空')
            return { isValid: false, errors }
        }

        // 检查图表类型声明
        const lines = code.split('\n')
        const firstLine = lines[0].trim()

        if (!firstLine.match(/^(flowchart|graph|stateDiagram|sequenceDiagram|classDiagram|erDiagram|pie)/)) {
            errors.push('缺少有效的图表类型声明')
        }

        // 检查语法错误
        const syntaxErrors = this.checkSyntaxErrors(code)
        errors.push(...syntaxErrors)

        return { isValid: errors.length === 0, errors }
    }

    /**
     * 检查语法错误
     */
    private checkSyntaxErrors(code: string): string[] {
        const errors: string[] = []
        const lines = code.split('\n')

        lines.forEach((line, index) => {
            const trimmed = line.trim()
            if (!trimmed || trimmed.startsWith('%%')) return

            // 检查括号匹配
            const openBrackets = (trimmed.match(/\[/g) || []).length
            const closeBrackets = (trimmed.match(/\]/g) || []).length

            if (openBrackets !== closeBrackets) {
                errors.push(`第${index + 1}行: 方括号不匹配`)
            }

            // 检查连接语法
            if (trimmed.includes('-->') || trimmed.includes('---')) {
                const parts = trimmed.split(/-->|---/)
                if (parts.length === 2) {
                    const from = parts[0].trim()
                    const to = parts[1].trim()

                    if (!from || !to) {
                        errors.push(`第${index + 1}行: 连接语法不完整`)
                    }
                }
            }
        })

        return errors
    }

    /**
     * 获取代码统计信息
     */
    getCodeStatistics(code: string): {
        lines: number
        nodes: number
        connections: number
        directives: number
        complexity: 'low' | 'medium' | 'high'
    } {
        const lines = code.split('\n').filter(line => line.trim()).length
        const nodes = (code.match(/\w+\[|\w+\(|\w+\{/g) || []).length
        const connections = (code.match(/-->|---|-\.-|==>/g) || []).length
        const directives = (code.match(/class |style |click /g) || []).length

        let complexity: 'low' | 'medium' | 'high' = 'low'
        if (nodes > 20 || connections > 30) {
            complexity = 'high'
        } else if (nodes > 10 || connections > 15) {
            complexity = 'medium'
        }

        return { lines, nodes, connections, directives, complexity }
    }
}

/**
 * 高级Mermaid代码生成器
 * 扩展基础代码生成器，提供更多高级功能
 */
// export class AdvancedMermaidCodeGenerator extends MermaidCodeGenerator {

//     /**
//      * 批量生成多个图表
//      */
//     generateBatch(visualCharts: any[]): { code: string; errors: string[] }[] {
//         return visualCharts.map(chart => {
//             try {
//                 const code = this.generate(chart)
//                 const validation = this.validateGeneratedCode(code)
//                 return {
//                     code,
//                     errors: validation.errors
//                 }
//             } catch (error) {
//                 return {
//                     code: '',
//                     errors: [error instanceof Error ? error.message : '未知错误']
//                 }
//             }
//         })
//     }

//     /**
//      * 生成带样式的代码
//      */
//     generateWithStyles(visualChart: any, styles: StyleConfig): string {
//         const baseCode = this.generate(visualChart)
//         const styleCode = this.generateStyles(styles)
//         return baseCode + styleCode
//     }

//     /**
//      * 生成样式代码
//      */
//     private generateStyles(styles: StyleConfig): string {
//         if (!styles || Object.keys(styles).length === 0) {
//             return ''
//         }

//         const styleLines: string[] = []

//         // 生成节点样式
//         if (styles.nodes) {
//             Object.entries(styles.nodes).forEach(([nodeId, style]) => {
//                 const styleProps = this.formatStyleProperties(style)
//                 styleLines.push(`    style ${nodeId} ${styleProps}`)
//             })
//         }

//         // 生成类样式
//         if (styles.classes) {
//             Object.entries(styles.classes).forEach(([className, style]) => {
//                 const styleProps = this.formatStyleProperties(style)
//                 styleLines.push(`    classDef ${className} ${styleProps}`)
//             })
//         }

//         // 生成类绑定
//         if (styles.classBindings) {
//             Object.entries(styles.classBindings).forEach(([nodeId, className]) => {
//                 styleLines.push(`    class ${nodeId} ${className}`)
//             })
//         }

//         return styleLines.length > 0 ? '\n' + styleLines.join('\n') + '\n' : ''
//     }

//     /**
//      * 格式化样式属性
//      */
//     private formatStyleProperties(style: StyleProperties): string {
//         const props: string[] = []

//         if (style.fill) props.push(`fill:${style.fill}`)
//         if (style.stroke) props.push(`stroke:${style.stroke}`)
//         if (style.strokeWidth) props.push(`stroke-width:${style.strokeWidth}`)
//         if (style.color) props.push(`color:${style.color}`)
//         if (style.fontSize) props.push(`font-size:${style.fontSize}`)
//         if (style.fontWeight) props.push(`font-weight:${style.fontWeight}`)

//         return props.join(',')
//     }

//     /**
//      * 优化生成的代码
//      */
//     optimizeCode(code: string): string {
//         let optimized = code

//         // 移除重复的节点定义
//         optimized = this.removeDuplicateNodes(optimized)

//         // 优化连接顺序
//         optimized = this.optimizeConnectionOrder(optimized)

//         // 格式化代码
//         optimized = this.formatCode(optimized)

//         return optimized
//     }

//     /**
//      * 移除重复的节点定义
//      */
//     private removeDuplicateNodes(code: string): string {
//         const lines = code.split('\n')
//         const nodeDefinitions = new Set<string>()
//         const filteredLines: string[] = []

//         lines.forEach(line => {
//             const trimmed = line.trim()

//             // 检查是否是节点定义
//             const nodeMatch = trimmed.match(/^(\w+)(\[.*?\]|\(.*?\)|\{.*?\}|\(\(.*?\)\))/)
//             if (nodeMatch) {
//                 const nodeId = nodeMatch[1]
//                 if (!nodeDefinitions.has(nodeId)) {
//                     nodeDefinitions.add(nodeId)
//                     filteredLines.push(line)
//                 }
//             } else {
//                 filteredLines.push(line)
//             }
//         })

//         return filteredLines.join('\n')
//     }

//     /**
//      * 优化连接顺序
//      */
//     private optimizeConnectionOrder(code: string): string {
//         const lines = code.split('\n')
//         const headerLines: string[] = []
//         const nodeLines: string[] = []
//         const connectionLines: string[] = []
//         const directiveLines: string[] = []

//         lines.forEach(line => {
//             const trimmed = line.trim()

//             if (trimmed.startsWith('flowchart') || trimmed.startsWith('graph') || trimmed.startsWith('stateDiagram')) {
//                 headerLines.push(line)
//             } else if (trimmed.match(/^(\w+)(\[.*?\]|\(.*?\)|\{.*?\}|\(\(.*?\)\))$/)) {
//                 nodeLines.push(line)
//             } else if (trimmed.match(/^(\w+)\s*(-->|---|-\.-|==>)/)) {
//                 connectionLines.push(line)
//             } else if (trimmed.match(/^(style|class|classDef|click)/)) {
//                 directiveLines.push(line)
//             } else {
//                 headerLines.push(line)
//             }
//         })

//         return [
//             ...headerLines,
//             ...nodeLines,
//             ...connectionLines,
//             ...directiveLines
//         ].join('\n')
//     }

//     /**
//      * 从模板生成代码
//      */
//     generateFromTemplate(template: FlowchartTemplate, data: TemplateData): string {
//         try {
//             // 替换模板中的占位符
//             let code = template.code || this.generateTemplateCode(template)

//             // 替换数据占位符
//             if (data.variables) {
//                 Object.entries(data.variables).forEach(([key, value]) => {
//                     const placeholder = `{{${key}}}`
//                     code = code.replace(new RegExp(placeholder, 'g'), String(value))
//                 })
//             }

//             // 替换节点占位符
//             if (data.nodes) {
//                 data.nodes.forEach((node, index) => {
//                     const nodeId = `node${index + 1}`
//                     const placeholder = `{{${nodeId}}}`
//                     code = code.replace(new RegExp(placeholder, 'g'), node.text)
//                 })
//             }

//             return code
//         } catch (error) {
//             console.error('从模板生成代码失败:', error)
//             throw error
//         }
//     }

//     /**
//      * 生成模板代码
//      */
//     private generateTemplateCode(template: FlowchartTemplate): string {
//         const visualChart = {
//             type: 'flowchart',
//             direction: 'TD',
//             nodes: template.nodes,
//             connections: template.connections,
//             directives: []
//         }

//         return this.generate(visualChart)
//     }

//     /**
//      * 分析代码复杂度
//      */
//     analyzeComplexity(code: string): ComplexityAnalysis {
//         const stats = this.getCodeStatistics(code)
//         const lines = code.split('\n')

//         // 计算嵌套深度
//         let maxDepth = 0
//         let currentDepth = 0

//         lines.forEach(line => {
//             const trimmed = line.trim()
//             if (trimmed.includes('subgraph')) {
//                 currentDepth++
//                 maxDepth = Math.max(maxDepth, currentDepth)
//             } else if (trimmed === 'end') {
//                 currentDepth--
//             }
//         })

//         // 计算连接密度
//         const connectionDensity = stats.nodes > 0 ? stats.connections / stats.nodes : 0

//         // 计算复杂度分数
//         const complexityScore = stats.nodes * 1 + stats.connections * 2 + maxDepth * 5

//         return {
//             nodeCount: stats.nodes,
//             connectionCount: stats.connections,
//             maxDepth,
//             connectionDensity,
//             complexityScore,
//             complexity: stats.complexity,
//             recommendations: this.generateComplexityRecommendations(stats, maxDepth, connectionDensity)
//         }
//     }

//     /**
//      * 生成复杂度建议
//      */
//     private generateComplexityRecommendations(stats: any, maxDepth: number, connectionDensity: number): string[] {
//         const recommendations: string[] = []

//         if (stats.nodes > 30) {
//             recommendations.push('考虑将图表分解为多个子图表')
//         }

//         if (connectionDensity > 3) {
//             recommendations.push('连接密度过高，考虑简化连接关系')
//         }

//         if (maxDepth > 3) {
//             recommendations.push('嵌套层级过深，考虑扁平化结构')
//         }

//         if (stats.complexity === 'high') {
//             recommendations.push('图表复杂度较高，建议使用子图功能进行组织')
//         }

//         return recommendations
//     }

//     /**
//      * 导出为不同格式
//      */
//     exportToFormat(code: string, format: ExportFormat): string {
//         switch (format) {
//             case 'mermaid':
//                 return code
//             case 'markdown':
//                 return this.exportToMarkdown(code)
//             case 'html':
//                 return this.exportToHtml(code)
//             case 'json':
//                 return this.exportToJson(code)
//             default:
//                 return code
//         }
//     }

//     /**
//      * 导出为Markdown格式
//      */
//     private exportToMarkdown(code: string): string {
//         return `\`\`\`mermaid\n${code}\n\`\`\``
//     }

//     /**
//      * 导出为HTML格式
//      */
//     private exportToHtml(code: string): string {
//         return `<div class="mermaid">\n${code}\n</div>`
//     }

//     /**
//      * 导出为JSON格式
//      */
//     private exportToJson(code: string): string {
//         const analysis = this.analyzeComplexity(code)
//         const stats = this.getCodeStatistics(code)

//         return JSON.stringify({
//             code,
//             statistics: stats,
//             complexity: analysis,
//             timestamp: new Date().toISOString()
//         }, null, 2)
//     }

//     /**
//      * 生成代码差异
//      */
//     generateDiff(oldCode: string, newCode: string): CodeDiff {
//         const oldLines = oldCode.split('\n')
//         const newLines = newCode.split('\n')

//         const additions: string[] = []
//         const deletions: string[] = []
//         const modifications: string[] = []

//         // 简单的差异检测
//         newLines.forEach(line => {
//             if (!oldLines.includes(line)) {
//                 additions.push(line)
//             }
//         })

//         oldLines.forEach(line => {
//             if (!newLines.includes(line)) {
//                 deletions.push(line)
//             }
//         })

//         return {
//             additions,
//             deletions,
//             modifications,
//             hasChanges: additions.length > 0 || deletions.length > 0 || modifications.length > 0
//         }
//     }
// }

/**
 * 便捷函数：获取流程图模板
 */
// export async function getFlowchartTemplates(): Promise<FlowchartTemplate[]> {
//     try {
//         const templatesModule = await import('../templates/flowchart-templates.json')
//         const templatesData = templatesModule.default

//         // 简化处理，提取基础模板
//         const templates: FlowchartTemplate[] = []

//         if (templatesData.categories) {
//             for (const category of templatesData.categories) {
//                 for (const template of category.templates || []) {
//                     templates.push({
//                         id: template.id,
//                         name: template.name,
//                         description: template.description,
//                         category: category.name,
//                         nodes: [], // 简化处理，先返回空数组
//                         connections: []
//                     })
//                 }
//             }
//         }

//         return templates
//     } catch (error) {
//         console.error('Failed to load flowchart templates:', error)
//         return []
//     }
// }

// 重新导出所有需要的类型
export type {
    MermaidNode,
    MermaidConnection,
    CompatibilityIssue,
    FlowchartTemplate,
    ChartType,
    MermaidSyntaxMapping,
    ChartTypeMapping,
    NodeTypeMapping,
    ConnectionTypeMapping,
    TemplateData,
    StyleConfig,
    StyleProperties,
    ComplexityAnalysis,
    ExportFormat,
    CodeDiff,
    CodeGenerationOptions,
    CodeGenerationResult,
    BatchGenerationResult
} from '../types'


